<cfscript>
component extends="SimpleDBObject" {

	function init(sdb) {
		variables.sdb = sdb;
		variables.domain = "";
		variables.columns = "*";
		variables.where = "";
		variables.order = "";
		variables.limit = 100;
		variables.nextToken = "xxx";
		return this;
	}
	
	function domain(domain) {
		variables.domain = domain;
		return this;
	}
	
	function keys(keylist) {
		variables.columns = keylist;
		return this;
	}
	
	function where(whereclause) {
		variables.where = whereclause;
		return this;
	}
	
	function andWhere(whereclause) {
		variables.where &= " AND "&whereclause;
		return this;
	}
	
	function orderby(orderclause) {
		variables.order = orderclause;
		return this;
	}
	
	function limit(limitclause) {
		variables.limit = limitclause;
		return this;
	}
	
	function toSql() {
		var sqlstr = "select #variables.columns# from #variables.domain#";
		if (variables.where.length()) sqlstr &= " where #variables.where#";
		if (variables.order.length()) sqlstr &= " order by  #variables.order#";
		if (variables.limit gt 0) sqlstr &= " limit #variables.limit#";
		return sqlstr;
	}
		
	function hasMore() {
		return StructKeyExists(variables, "request") and Len(variables.request.getNextToken());
	}
	
	function execute(sql=toSql()) {
		var items = [];
		if (!StructKeyExists(variables, "request"))
			variables.request = _jobj("com.amazonaws.services.simpledb.model.SelectRequest").init(sql);
			
		local.response = variables.sdb.doSync("select", variables.request);
		if (!IsNull(local.response.getNextToken())) {
			variables.request.setNextToken(local.response.getNextToken());
		}
		//variables.nextToken = IsNull(local.response.getNextToken())?"":local.response.getNextToken();
		loop array="#local.response.getItems()#" index="local.a" {
			ArrayAppend(items, new CachedItem(variables.sdb, variables.domain, local.a.getName()).withAttributes(local.a.getAttributes()));
		}
		return items;
	}
	

}
</cfscript>